package com.stu.config.shiro;

import com.stu.pojo.Permission;
import com.stu.pojo.Role;
import com.stu.pojo.User;
import com.stu.service.RoleAndPermManageService;
import com.stu.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleAndPermManageService ropService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        String username = SecurityUtils.getSubject().getPrincipal().toString();
        List<Role> roles = ropService.getRolesByUname(username);
        for(Role role : roles){
            info.addRole(role.getName());//授予角色
            for(Permission perm : ropService.getPermsByRname(role.getName())){
                info.addStringPermission(perm.getName());//授予权限
            }
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        String password = token.getCredentials().toString();
        User user = userService.getUserByUsername(username);
        if(user==null) return null;//抛出UnknownAccountException
        //加密：password用相同加密过程进行加密生成密文，与user.getPassword()比较

        return new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                this.getName()
        );
    }
}
